package hust.iamk.lock;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.OnScanCompletedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.cooliris.media.Gallery;
import com.cooliris.media.GridLayer;
import com.cooliris.media.LocalDataSource;

public class UnlockFileTask extends AsyncTask<String, String, String> {
	
	ProgressDialog pdLockFile;

	Context mContext;
	GridLayer mGridLayer;
	ArrayList<String> arrFilePath;
	long totalLengthFile = 0;
	int currentLen = 0;
	
	boolean LOCK_FAILED = true;
	boolean flag = true; // Check show/hide progress bar
	
	public UnlockFileTask(Context mContext, ArrayList<String> arrFilePath, GridLayer mGridLayer, boolean flag) {
		// TODO Auto-generated constructor stub
		this.flag = flag;
		this.arrFilePath = arrFilePath;
		this.mContext = mContext;
		this.mGridLayer = mGridLayer;
		// Get all length file
		for(int i = 0; i < arrFilePath.size();i++){
			File f = new File(arrFilePath.get(i));
			if(f.exists()){
				totalLengthFile += f.length();
			}
		}
	}
	
	@SuppressWarnings("deprecation")
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		if(flag){
			pdLockFile = new ProgressDialog(mContext);
			pdLockFile.setTitle("Unlocking file");
			pdLockFile.setMessage("File unlock will be store in Camera album! Please wait...");
			pdLockFile.setIndeterminate(false);
			pdLockFile.setMax(100);
			pdLockFile.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			pdLockFile.setCancelable(false);
			pdLockFile.setCanceledOnTouchOutside(false);
			pdLockFile.setButton("Do in background", new OnClickListener() {
	            @Override
	            public void onClick(DialogInterface dialog, int which) {
	            	pdLockFile.dismiss();
	            }
	        });
			pdLockFile.show();
		}
	}

	/**
	 * Lock file in background thread
	 * */
	@Override
	protected String doInBackground(String... mItem) {
		try {
			for(int i = 0; i < arrFilePath.size(); i++){
				String fileNameSrc = SecurityFileUtils.getFileName(arrFilePath.get(i), 0);
				File fsrc = new File(arrFilePath.get(i));
				File fdes = new File(LocalDataSource.LOCK_BUCKET_FOLDER +"/" + fileNameSrc.replace("iamk", "."));
				Log.d("lock", fsrc.getAbsolutePath() + " // " + fdes.getAbsolutePath());
				if(!fsrc.getAbsolutePath().toString().equals(fdes.getAbsolutePath().toString())){
		            InputStream is=new FileInputStream(fsrc);
		            OutputStream os=new FileOutputStream(fdes);
		            byte[] buff=new byte[1024];
		            int len;
		            while((len = is.read(buff)) > 0){
		                os.write(buff,0,len);
		                currentLen += len;
		                publishProgress(""+(int)((currentLen*100)/totalLengthFile));
		            }
		            
		            mediaScan(fdes, mContext);
					
		            is.close();
		            os.close();
		        }
			}
			LOCK_FAILED = false;
		} catch (Exception e) {
			LOCK_FAILED = true;
			e.printStackTrace();
		} 
        return null;
	}
	
	/**
	 * Updating progress bar
	 * */
	protected void onProgressUpdate(String... progress) {
		// setting progress percentage
		if(flag)
			pdLockFile.setProgress(Integer.parseInt(progress[0]));
   }

	@Override
	protected void onPostExecute(String mItem) {
		if (flag && pdLockFile != null && pdLockFile.isShowing()) 
			 pdLockFile.dismiss();
		// Delete original file
		Log.d("lock", "Lock failed: " + LOCK_FAILED);
		if(!LOCK_FAILED){
//			mGridLayer.deleteSelection();
		}else{
			Toast t = new  Toast(mContext);
			t.makeText(mContext, "Unlock failed! Re-unlock again", Toast.LENGTH_SHORT).setDuration(1000);
			t.show();
		}
	}
	
	public void mediaScan(File file,Context mContext) {
		MediaScannerConnection.scanFile(mContext,
				new String[] { file.getAbsolutePath() }, null,
				new OnScanCompletedListener() {
					@Override
					public void onScanCompleted(String path, Uri uri) {
						Log.d("MediaScanWork", "file " + path + " was scanned seccessfully: " + uri);
					}
				});
	}
}


